package com.caiyi.tips.core.servlet;

import com.caiyi.tips.core.servlet.yzm.VerificationCodeTool;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
public class YzmServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processRequest(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processRequest(req,resp);
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
		try {
			resp.setContentType("image/jpeg");
			resp.setHeader("Pragma", "No-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", 0L);
		    HttpSession localHttpSession = req.getSession(true);
		    VerificationCodeTool vct = new VerificationCodeTool();
		    BufferedImage image = vct.drawVerificationCodeImage();
		    ServletOutputStream localServletOutputStream = resp.getOutputStream();
		    localHttpSession.setAttribute("rand", vct.getXyresult()+"");
			localHttpSession.setAttribute("randErrCount", 0);
			ImageIO.write(image, "JPEG", localServletOutputStream);
			localServletOutputStream.flush();
		    localServletOutputStream.close();
		    log.info("验证码生成成功,内容:"+vct.getRandomString()+" 结果:"+vct.getXyresult());
		} catch (IOException e) {
			log.error("创建验证码失败",e);
		}
	}
}
